import { Inject, Injectable } from "@nestjs/common";
import Redis, { RedisOptions } from "ioredis";
import { Utils } from "./util";

@Injectable()
export class RedisService {
    defaultClient: string;
    constructor(
        @Inject('CLIEN_NAME') name: string, 
        @Inject('CONFIG_OPTIONS') options: RedisOptions
    ) {
        // 在构造函数中初始化 Redis 客户端
        Utils.getInterface().set(name, options)
        this.defaultClient = Utils.getInterface().getFirst()
      }
     /**
      * 获取redis客服端
      * @param name redis连接名
      * @returns 
      */
      getClient(name): Redis {
        return Utils.getInterface().get(name);
      }
     
      async setValue(key: string, value: any, clientName = this.defaultClient): Promise<void> {
        if (value !== null && typeof value === 'object') {
            await Utils.getInterface().get(clientName).set(key, JSON.stringify(value));
        } else {
            await Utils.getInterface().get(clientName).set(key, value);
        } 
      }
     
      async getValue(key: string, clientName = this.defaultClient): Promise<string> {
        const result = await Utils.getInterface().get(clientName).get(key)
        try {
            return JSON.parse(result);
        } catch (error) {
            return result
        }
      }
}